package com.xidian.zhiancloud.service.chemicalsManagement.chemicalManager.dangerousPart;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xidian.zhiancloud.constant.DangerousManagementConstant;
import com.xidian.zhiancloud.dao.DangerousChemicalInventoryChangeRecordMapper;
import com.xidian.zhiancloud.dao.DangerousChemicalStorageMapper;
import com.xidian.zhiancloud.dao.DangerousChemicalWarehouseOutMapper;
import com.xidian.zhiancloud.dao.syset.SysPositionMapper;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.model.*;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.SysPosition;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.qo.chemicalsManagement.DangerousChemicalStorageQO;
import com.xidian.zhiancloud.service.chemicalsManagement.chemicalManager.CodeService;
import com.xidian.zhiancloud.service.user.UserService;
import com.xidian.zhiancloud.service.user.usermanage.OrganizationService;
import com.xidian.zhiancloud.vo.chemicalsManagement.DangerousChemicalInfoVO;
import com.xidian.zhiancloud.vo.chemicalsManagement.DangerousChemicalStorageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: Egoist
 * @Date: 2020/11/10 17:00
 */

@Service
public class DangerousChemicalStorageService extends ServiceImpl<DangerousChemicalStorageMapper, DangerousChemicalStorage> implements IService<DangerousChemicalStorage> {

    @Autowired
    private DangerousChemicalStorageMapper dangerousChemicalStorageMapper;
    @Autowired
    private CodeService codeService;
    @Autowired
    private DangerousChemicalInventoryChangeRecordMapper dangerousChemicalInventoryChangeRecordMapper;
    @Autowired
    private DangerCategoryService dangerCategoryService;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private SysPositionMapper sysPositionMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private DangerousChemicalWarehouseOutMapper dangerousChemicalWarehouseOutMapper;
    @Autowired
    private DangerousChemicalInfoService dangerousChemicalInfoService;

    public boolean addOrUpdate(DangerousChemicalStorage dangerousChemicalStorage, Long storageId){
        DangerousChemicalInventoryChangeRecord dangerousChemicalInventoryChangeRecord = new DangerousChemicalInventoryChangeRecord();
        dangerousChemicalInventoryChangeRecord.setCompanyId(dangerousChemicalStorage.getCompanyId());
        dangerousChemicalInventoryChangeRecord.setStorageQuantity(dangerousChemicalStorage.getStorageQuantity());
        dangerousChemicalInventoryChangeRecord.setSupplier(dangerousChemicalStorage.getSupplier());
        dangerousChemicalInventoryChangeRecord.setContactNumber(dangerousChemicalStorage.getContactInfo());
        dangerousChemicalInventoryChangeRecord.setStoragePersonId(storageId);

        String code = codeService.getChemicalStorageCode(dangerousChemicalStorage.getCompanyId());

        dangerousChemicalInventoryChangeRecord.setStorageTime(new Date(System.currentTimeMillis()));
        dangerousChemicalInventoryChangeRecord.setStorageCode(code);


        Map<String,Long> map = new HashMap<>(16);
        map.put("company_id", dangerousChemicalStorage.getCompanyId());
        map.put("chemical_id", dangerousChemicalStorage.getChemicalId());
        map.put("organization_id", dangerousChemicalStorage.getOrganizationId());
        map.put("position_id", dangerousChemicalStorage.getPositionId());
        map.put("manager_id", dangerousChemicalStorage.getManagerId());

        QueryWrapper<DangerousChemicalStorage> qw = new QueryWrapper();
        qw.allEq(map);
        DangerousChemicalStorage dcs = dangerousChemicalStorageMapper.selectOne(qw);
        boolean res;
        Long sId;

        if (dcs == null) {
            res = save(dangerousChemicalStorage);
            sId = dangerousChemicalStorage.getId();
        } else {
            BigDecimal quantity = dcs.getStorageQuantity().add(dangerousChemicalStorage.getStorageQuantity());
            dcs.setStorageQuantity(quantity);
            res = updateById(dcs);
            sId = dcs.getId();
        }
        dangerousChemicalInventoryChangeRecord.setStorageId(sId);
        dangerousChemicalInventoryChangeRecordMapper.insert(dangerousChemicalInventoryChangeRecord);

        return res;
    }

    public IPage<DangerousChemicalStorageVO> getListByQueryObject(DangerousChemicalStorageQO dangerousChemicalStorageQO) {
        Page<DangerousChemicalStorageVO> page = new Page<>(dangerousChemicalStorageQO.getCurrent(), dangerousChemicalStorageQO.getSize());
        OrderItem orderItem = new OrderItem();
        orderItem.setColumn("create_time").setAsc(false);
        page.getOrders().add(orderItem);
        IPage<DangerousChemicalStorageVO> iPage = dangerousChemicalStorageMapper.getListByQO(page, dangerousChemicalStorageQO);
        List<DangerousChemicalStorageVO> records = iPage.getRecords();
        List<DangerousChemicalStorageVO> ans = new ArrayList<>();
        records.forEach(t -> {
            t.setStrQuantity(t.getStorageQuantity().toString() + DangerousManagementConstant.QuantityUnit.get(t.getUnit()));
            ans.add(t);
        });
        iPage.setRecords(ans);
        return iPage;
    }

    public Map<Long, String> getTypeList(Long companyId) {
        LambdaQueryWrapper<DangerCategory> query = Wrappers.<DangerCategory>lambdaQuery();
        query.eq(DangerCategory::getCompanyId, companyId);
        List<DangerCategory> list = dangerCategoryService.list(query);
        return list.stream().collect(Collectors.toMap(DangerCategory::getId, DangerCategory::getName));
    }


    public List<Map> getRecordById(Long id, Long companyId) {
        List list = new ArrayList();
        //查询入库台账
        LambdaQueryWrapper<DangerousChemicalInventoryChangeRecord> query = Wrappers.<DangerousChemicalInventoryChangeRecord>lambdaQuery();
        query.eq(DangerousChemicalInventoryChangeRecord::getStorageId, id).eq(DangerousChemicalInventoryChangeRecord::getCompanyId, companyId);
        List<DangerousChemicalInventoryChangeRecord> records = dangerousChemicalInventoryChangeRecordMapper.selectList(query);
        if (records != null){
            for (DangerousChemicalInventoryChangeRecord record : records) {
                Map map = new HashMap();
                map.put("time", record.getStorageTime());
                SysUser user = userService.getById(record.getStoragePersonId());
                DangerousChemicalStorage dangerousChemicalStorage = dangerousChemicalStorageMapper.selectById(record.getStorageId());
                DangerousChemicalInfo info = dangerousChemicalInfoService.getById(dangerousChemicalStorage.getChemicalId());
                String content = user == null ? "该用户已删除" : user.getName() + " 入库" + record.getStorageQuantity() +
                        DangerousManagementConstant.QuantityUnit.get(info.getUnit()) + ", 供应商: " + record.getSupplier();
                map.put("content", content);
                list.add(map);
            }
        }

        //查询出库台账
        LambdaQueryWrapper<DangerousChemicalWarehouseOut> queryOut = Wrappers.<DangerousChemicalWarehouseOut>lambdaQuery();
        queryOut.eq(DangerousChemicalWarehouseOut::getStorageId, id).eq(DangerousChemicalWarehouseOut::getCompanyId, companyId).gt(DangerousChemicalWarehouseOut::getState, 2);
        List<DangerousChemicalWarehouseOut> outRecords = dangerousChemicalWarehouseOutMapper.selectList(queryOut);
        if (outRecords != null) {
            for (DangerousChemicalWarehouseOut outRecord : outRecords) {
                Map map = new HashMap();
                map.put("time", outRecord.getOutTime());
                SysUser user1 = userService.getById(outRecord.getOuterId());
                DangerousChemicalStorage dangerousChemicalStorage = dangerousChemicalStorageMapper.selectById(outRecord.getStorageId());
                DangerousChemicalInfo info = dangerousChemicalInfoService.getById(dangerousChemicalStorage.getChemicalId());
                String content = user1 == null ? "该用户已删除" : user1.getName() + " 出库" + outRecord.getRealQuantity() +
                        DangerousManagementConstant.QuantityUnit.get(info.getUnit()) + ", 使用地点: " + outRecord.getUsePlace();
                map.put("content", content);
                list.add(map);
            }
        }

        return list;
    }

    public DangerousChemicalInfoVO getInfoById(Long id) {
        Long chemicalId = getById(id).getChemicalId();
        return dangerousChemicalInfoService.getVOById(chemicalId);
    }

    public DangerousChemicalStorageVO getStorageVOById(Long id) {
        DangerousChemicalStorageVO vo = new DangerousChemicalStorageVO();
        DangerousChemicalStorage storage = getById(id);

        DangerousChemicalInfo info = dangerousChemicalInfoService.getById(storage.getChemicalId());
        Organization org = organizationService.getById(storage.getOrganizationId());
        SysUser mag = userService.getById(storage.getManagerId());
        SysPosition pos = sysPositionMapper.selectById(storage.getPositionId());

        BeanUtils.copyProperties(storage, vo);
        vo.setChemicalName(info.getName());
        vo.setManagerName(mag == null ? "该用户已删除" : mag.getName());
        vo.setDepartmentName(org == null ? "该部门已删除" : org.getName());
        vo.setPositionName(pos == null ? "该地址已删除" : pos.getName());
        return vo;
    }
}

